package com.rupertjones.globalcron.config;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Properties;

public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {

    private static final Logger LOG = Logger.getLogger(PropertyPlaceholder.class);
    private volatile String propertiesLocation;

    public PropertyPlaceholder() {
        this.propertiesLocation = System.getenv("GLOBAL_CRON_HOME");
    }

    protected String resolvePlaceholder(String placeholder, Properties props) {

        try {
            Properties properties = new Properties();
            String outsideConfiguration = propertiesLocation + "/global-cron.properties";

            InputStream is = null;
            try {
                is = new FileInputStream(new File(outsideConfiguration));
            } catch (FileNotFoundException fnfe) {
                LOG.error("Couldn't find properties file global-cron.properties at " + propertiesLocation);
                return null;
            }

            properties.load(is);
            String property = properties.getProperty(placeholder);

            if (property == null) {
                throw new RuntimeException("Couldn't find property [" + placeholder + "]. Returning an empty string.");
            }

            String displayValue = property;

            if (placeholder.contains("pass")) {
                displayValue = "******";
            }

            LOG.info("Loading property [" + placeholder + "] with value [" + displayValue + "].");
            return property;
        } catch (UnknownHostException e) {
            LOG.error(e);
        } catch (IOException e) {
            LOG.error(e);
        }
        LOG.error("Could not find configuration property [" + placeholder + "]");
        return null;
    }
}
